from _winreg import *

class RegValue(object):
  def __init__(self, name, value, type):
    self.name = name
    self.value = value
    self.type = type
  
  def __unicode__(self): return self.value
  
  def __repr__(self):
    return u"RegValue(%s,%s,%s)"%(repr(self.name),repr(self.value),repr(self.type))

class RegKey(object):
  def __init__(self, key, name=""):
    self.parent_key = key
    self.name = name
    
  @property
  def key(self):
    if not hasattr(self,'_key'):
      self._key = OpenKey(self.parent_key, self.name, 0, KEY_READ|KEY_SET_VALUE)
    return self._key

  def __unicode__(self):
    return self.name

  def __repr__(self):
    return "RegKey(%s,%s)"%(self.parent_key==HKEY_LOCAL_MACHINE and 'HKEY_LOCAL_MACHINE' or
                            self.parent_key==HKEY_CURRENT_USER and 'HKEY_CURRENT_USER' or self.parent_key, 
                            repr(self.name))
                            
  def __getitem__(self, name):
    try:
      return QueryValueEx(self.key, name)[0]
    except:
      return None
    
  def value(self, name, default=None):
    try:
      return QueryValueEx(self.key, name)[0]
    except:
      return default
    
  def __setitem__(self, name, value):
    SetValueEx(self.key, name, "", REG_SZ, value)

  def _enum(self, enum_func):
    try:
      n=0
      while True:
        yield enum_func(self.key, n)
        n+=1
    except Exception,e:
      pass
        
  def values(self):
    return iter(self._enum(lambda k,n:RegValue(*EnumValue(k,n))))
  
  def keys(self):
    return iter(self._enum(lambda k,n:RegKey(self.key,EnumKey(k,n))))
  
  def __iter__(self):
    return self.keys()
    
  def remove(self):
    DeleteKey(self.parent_key, self.name)
  
  def create_subkey(self, name):
    return RegKey(CreateKey(self.key, name))

if __name__ == "__main__":
  UPGR_CODES="Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\UpgradeCodes"
  key = RegKey(HKEY_LOCAL_MACHINE,UPGR_CODES)
  for subk in key:
    for x in subk.values():
      print x.name
  
